import { goodsList,goodsCount } from "../../../request/api"
const state={
goodslist:[],
size:2,
page:1,
count:0
}
const getters={
    getGoodsList(state){
        return state.goodslist
    },
    getCount(state){
        return state.count
    },
    getSize(state){
        return state.size
    }
}
const mutations={
    REQ_GOODSLIST(state,payload){
        state.goodslist=payload
    },
    REQ_GETCOUNT(state,payload){
        state.count=payload
    },
    CHANGE_PAGE(state,payload){
        state.page=payload
    }
}
const actions={
    //获取商品列表
    getGoodsListAction(context){
        goodsList({
            size:context.state.size,
            page:context.state.page
        }).then(res=>{
            if(res.code==200){
                context.commit('REQ_GOODSLIST',res.list)
                if(context.state.page!=1&&res.list.length==0){
                    context.dispatch('changePageAction',context.state.page-1)
                }
            }
        })
    },
    // 获取总数
    getCountAction({commit}){
        goodsCount().then(res=>{
            if(res.code==200){
                commit('REQ_GETCOUNT',res.list[0].total)
            }
        })
    },
    // 切换页码
    changePageAction(context,payload){
        context.commit('CHANGE_PAGE',payload)
        context.dispatch('getGoodsListAction')
    }
}

export default{
    state,
    getters,
    mutations,
    actions,
    namespaced:true
}